
import http, { baseParams } from "@/utils/request";
import { UrlConfirmLoanApply, UrlDataSmsCodeLogin, UrlGetAppConfig, UrlGetBankCodeList, UrlGetDataSmsCode, UrlGetLoanApplyDetailByAmount, UrlGetLoanLimit, UrlGetOtp, UrlGetReapyDetail, UrlGetReapyUrl, UrlGetUseState, UrlLogin, UrlLoginFacebook, UrlSaveEvent, UrlSaveFaceInfo, UrlSaveFrequentlyApps, UrlSaveProofContactList, UrlSaveUserLocation, UrlSendContractSms, UrlUploadImage } from "@/utils/apiUrl";
import { isEmptyObject, isEmptyString, toEventTagString, toList } from "@/utils/utils";
import { Toast } from "antd-mobile";
import { PageTag } from "@/utils/pageTag";
import { setChatMobile, setUserInfo } from "@/utils/storage";
import { isActionSelect, isAllStepsFinish, isProofBankAccount, isProofContact, isProofFace, isProofFrequentlyUsedApps, isProofMobile } from "./userState";
import AppConfig from "@/utils/appConfig";
import AppParams from "@/utils/appParams";
import { isString } from "formik";
import { AmountRange } from "@/utils/amountRange";
import uploadHttp from "@/utils/uploadRequest";

export const reqSaveEvent = async (type, remark = "") => {
    //组装参数
    const params = baseParams();
    const flag = process.env.REACT_APP_EVENT_PRODUCT_FLAG + "";
    if (type.startsWith(flag)) {
        params.type = toEventTagString(type);
    } else {
        params.type = flag + toEventTagString(type);
    }
    params.remark = remark;

    //发起请求
    await http.post(UrlSaveEvent, params);
    console.log("reqSaveEvent-end: =======" + type);
}

export const reqAppConfig = async (onCallback) => {
    //组装参数
    const params = baseParams();

    //发起请求
    const res = await http.post(UrlGetAppConfig, params);
    const resCode = parseInt(res.code);
    const resObj = res.obj;
    console.log("reqAppConfig-end: =======");

    //配置mobile列表
    const mobileContent = resObj.mobile;
    const mobileList = toList(mobileContent, ",");
    resObj.mobileList = mobileList;

    //配置email列表
    const emailContent = resObj.email;
    const emailList = toList(emailContent, ",");
    resObj.emailList = emailList;

    //保存
    const success = (resCode === 0)
    AppConfig.dataSource = resObj;

    //如果有错误，提示
    if (!success) {
        if (!isEmptyString(res.msg)) {
            Toast.show(res.msg, 1);
        }
    }

    onCallback && onCallback(success, resObj);
}

export const reqUserState = async (pageTag = PageTag.LAUNCH, onCallback) => {
    //组装参数
    const params = baseParams();

    if (pageTag === PageTag.LAUNCH_REFERRER) {
        params.token = AppParams.tid || "";
    }

    //发起请求
    const res = await http.post(UrlGetUseState, params);
    const resCode = parseInt(res.code);
    let resObj = res.obj;

    //保存
    const success = (resCode === 0);
    if (pageTag === PageTag.LAUNCH_REFERRER) {
        const userInfoResult = {};
        userInfoResult.token = params.token;
        userInfoResult.mobile = resObj.mobile || "";
        userInfoResult.userId = resObj.userId || "";

        // 保存用户信息
        setUserInfo(userInfoResult);
        setChatMobile(resObj.mobile + "");
    }

    //保存打点,只针对认证页
    if (success) {
        if (pageTag === PageTag.PROOF) {
            const steps = resObj.steps;
            if (isAllStepsFinish(steps)) {
                reqSaveEvent("PROOF_ALL_END");
            } else {
                const nextStep = steps[0];
                reqSaveEvent("PROOF_" + nextStep + "_START");
            }
        }

        //如果成功，格式化数据
        //当前手机号
        const readonlyMobile = resObj.readonlyMobile || null;
        console.log("reqUserState readonlyMobile: " + readonlyMobile);

        //当前手机号
        const wMobile = resObj.mobile || null;
        console.log("reqUserState wMobile: " + wMobile);

        //待做步骤
        const steps = resObj.steps;
        console.log("reqUserState" + steps);

        //如果所有步骤已完成, 直接返回
        if (isAllStepsFinish(steps)) {
            console.log("all finish");
            resObj.isProofFinish = true;
            resObj.pageTitle = "Info";
        } else {
            //取出第1个步骤
            const nextStep = steps[0];
            const allSteps = resObj.allSteps;
            const stepTitles = resObj.stepTitles;
            const indexOfNextStep = allSteps.indexOf(nextStep);
            const nextStepTitle = stepTitles[indexOfNextStep];
            console.log("reqUserState nextStep：" + nextStep + ", inex: " + indexOfNextStep + ", title: " + nextStepTitle);

            //如果是 mobile_verify，直接返回
            const mobileFormItem = {};
            if (isProofMobile(nextStep)) {
                mobileFormItem.pageTitle = nextStepTitle;
                mobileFormItem.stepTitle = nextStep;
                mobileFormItem.isProofFinish = false;
                mobileFormItem.readonlyMobile = readonlyMobile;
                resObj = mobileFormItem;
            }

            //如果是 frequently_apps，直接返回
            else if (isProofFrequentlyUsedApps(nextStep)) {
                mobileFormItem.pageTitle = nextStepTitle;
                mobileFormItem.stepTitle = nextStep;
                mobileFormItem.isProofFinish = false;
                mobileFormItem.readonlyMobile = readonlyMobile;
                resObj = mobileFormItem;
            }

            //如果是 selfie_invo
            else if (isProofFace(nextStep)) {
                mobileFormItem.pageTitle = nextStepTitle;
                mobileFormItem.stepTitle = nextStep;
                mobileFormItem.isProofFinish = false;
                mobileFormItem.readonlyMobile = readonlyMobile;
                resObj = mobileFormItem;
            }

            else if (isProofContact(nextStep)) {
                mobileFormItem.pageTitle = nextStepTitle;
                mobileFormItem.stepTitle = nextStep;
                mobileFormItem.isProofFinish = false;
                mobileFormItem.readonlyMobile = readonlyMobile;
                resObj = mobileFormItem;
            }

            else {
                //取出对应的字段信息
                const nextFormItem = resObj[nextStep];
                nextFormItem.pageTitle = nextStepTitle;
                nextFormItem.stepTitle = nextStep;
                nextFormItem.isProofFinish = false;
                nextFormItem.readonlyMobile = readonlyMobile;
                nextFormItem.mobile = wMobile

                //更新dataList中的content值，让它转变为受控状态
                nextFormItem.extDataList && nextFormItem.extDataList.forEach(item => {
                    item.content = "";
                    item.show = false;
                });

                //更新dataList中的content值，让它转变为受控状态
                nextFormItem.dataList && nextFormItem.dataList.forEach(item => {
                    item.content = "";
                    item.realContent = "";
                    item.show = false;

                    // 如果是银行字段，填充mobile
                    if (isProofBankAccount(nextStep)) {
                        if (item.paramName === "walletMobile") {
                            item.content = nextFormItem.mobile || "";
                            item.realContent = nextFormItem.mobile || "";
                        }
                    }

                    //工作、基本信息需要这些字段
                    item.stateContent = "";
                    item.cityContent = "";
                    item.areaContent = "";

                    //银行卡页需要这个字段
                    item.bankCodeContent = ""

                    //组装picker 列表数据 [[]]
                    if (item.values && isActionSelect(item.action)) {
                        item.values.forEach(value => {
                            value.label = value.title;
                        })
                        item.pickValues = [];
                        item.pickValues.push(item.values);
                    }
                });

                //判断是否为联系人步骤
                if (isProofContact(nextStep)) {
                    const itemCount = nextFormItem.itemCount;
                    const sectionList = [];
                    //nextFormItem.dataList=[{},{},{}]
                    for (let i = 0; i < itemCount; i++) {
                        let itemList = [];
                        let relationships = [...nextFormItem.relationShips[i]];
                        for (let itemIndex = 0; itemIndex < nextFormItem.dataList.length; itemIndex++) {
                            let oldItem = nextFormItem.dataList[itemIndex];
                            let newItem = { ...oldItem };

                            //如果action是 CONTACT_GROUP_RELATION, 组装values值
                            if (isActionSelect(oldItem.action)) {
                                //清空
                                newItem.values = [];
                                relationships.forEach(ship => {
                                    let relationship = {
                                        label: ship,
                                        title: ship,
                                        value: ship
                                    };
                                    newItem.values.push(relationship);
                                })

                                //组装picker 列表数据 [[]]
                                newItem.pickValues = [];
                                newItem.pickValues.push(newItem.values);
                            }

                            itemList[itemIndex] = newItem;
                        }
                        sectionList[i] = itemList;
                    }
                    nextFormItem.sectionList = sectionList;
                }
                console.log(nextFormItem);
                resObj = nextFormItem;
            }
        }
    }

    //如果有错误，提示
    if (!success) {
        if (!isEmptyString(res.msg)) {
            Toast.show(res.msg, 1);
        }
    }

    onCallback && onCallback(success, resObj, pageTag);
}

export const reqOtp = async (mobile, pageType = "LOGINPAGE", onCallback) => {
    //组装参数
    const params = baseParams();
    params.mobile = mobile;
    params.pageType = pageType;

    //发起请求
    const res = await http.post(UrlGetOtp, params);
    const resCode = parseInt(res.code);
    let resObj = {};
    if (res.obj) {
        if (!isString(res.obj)) {
            resObj = res.obj;
        }
    }

    //保存code，登录有用，判断是否为fb
    resObj.resCode = resCode;
    console.log("发送短信验证码回调-end: =======");

    //保存
    const success = (resCode === 0);

    //如果有错误，提示
    if ((resCode !== 2002) && (resCode !== 2001)) {
        if (!success) {
            if (!isEmptyString(res.msg)) {
                Toast.show(res.msg, 1);
            }
        }
    }

    onCallback && onCallback(success, resObj);
}

export const reqLogin = async (mobile, code, directLoginFlag = "NO", onCallback) => {
    //来源
    const dreferrer = document.referrer || "";

    //组装参数
    const params = baseParams();
    params.mobile = mobile || "";
    params.code = code || "";
    params.directLoginFlag = directLoginFlag || "";
    params.docReferrer = dreferrer || "";

    //发起请求
    const res = await http.post(UrlLogin, params);
    const resCode = parseInt(res.code);
    const resObj = res.obj;
    const resMsg = res.msg;
    console.log("reqLogin-end: =======");

    //保存
    const success = (resCode === 0);
    //如果有错误，提示
    if (!success) {
        if (!isEmptyString(resMsg)) {
            Toast.show(resMsg, 1);
        }
    }

    //保存本地
    if (success) {
        //保存号码
        resObj.mobile = mobile + "";
        setUserInfo(resObj);
        setChatMobile(mobile + "");
    }

    onCallback && onCallback(success, resObj);
}

export const reqFbUnionLogin = async (facebookId, pageType = "LOGINPAGE", onCallback) => {
    //来源
    const dreferrer = document.referrer || "";

    //组装参数
    const params = baseParams();
    params.facebookUserId = facebookId + "";
    params.pageType = pageType;
    params.docReferrer = dreferrer + "";

    //发起请求
    const res = http.post(UrlLoginFacebook, params);
    const resCode = parseInt(res.code);
    let resObj = {};
    if (res.obj) {
        if (!isString(res.obj)) {
            resObj = res.obj;
        }
    }

    const resMsg = res.msg;
    resObj.resCode = resCode;
    console.log("reqFbUnionLogin-end: =======");

    //保存
    const success = (resCode === 0);

    //如果有错误，提示
    if ((resCode !== 2002) && (resCode !== 2001)) {
        if (!success) {
            if (!isEmptyString(resMsg)) {
                Toast.show(resMsg, 1);
            }
        }
    }

    //保存本地
    if (success) {
        resObj.mobile = facebookId + "";
        setUserInfo(resObj);
        setChatMobile(facebookId + "");
    }

    onCallback && onCallback(success, resObj);
}

export const reqHomeCredit = async (onCallback) => {
    //组装参数
    const params = baseParams();

    //发起请求
    const res = await http.post(UrlGetLoanLimit, params);
    const resCode = parseInt(res.code);
    const resObj = res.obj;
    console.log("reqHomeCredit-end: =======");

    //保存
    const success = (resCode === 0);
    if (success) {
        const item0 = resObj.limit[0] || {};
        resObj.amount = item0.amount;
        resObj.desc = item0.desc;
        resObj.increasedAmount1 = item0.increasedAmount1;
        resObj.increasedAmount2 = item0.increasedAmount2;
    }

    //如果有错误，提示
    if (!success) {
        if (!isEmptyString(res.msg)) {
            Toast.show(res.msg, 1);
        }
    }
    onCallback && onCallback(success, resObj);
}

export const reqSaveLocation = async (longitude = "", latitude = "") => {
    //组装参数
    const params = baseParams();
    params.latitude = latitude;
    params.longitude = longitude;

    //发起请求
    await http.post(UrlSaveUserLocation, params);
    console.log("reqSaveLocation-end: =======");
}
export const reqBankCodeList = async (onCallback) => {
    //组装参数
    const params = baseParams();

    //发起请求
    const res = await http.post(UrlGetBankCodeList, params);
    const resCode = parseInt(res.code);
    const resObj = res.obj;
    console.log("reqBankCodeList-end: =======");

    //保存
    const success = (resCode === 0);

    //如果有错误，提示
    if (!success) {
        if (!isEmptyString(res.msg)) {
            Toast.show(res.msg, 1);
        }
    }

    onCallback && onCallback(success, resObj);
}

export const reqSaveProofData = async (apiUrl, proofData, curStep, onCallback) => {
    //组装参数
    const baseParam = baseParams();
    const params = { ...baseParam, ...proofData };

    //发起请求
    const res = await http.post(apiUrl, params);
    const resCode = parseInt(res.code);
    const resObj = res.obj;
    console.log("reqSaveProofData-end: =======");

    //保存
    const success = (resCode === 0);
    if (success) {
        //打点
        reqSaveEvent("PROOF_" + curStep + "_END");
    }

    //如果有错误，提示
    if (!success) {
        if (!isEmptyString(res.msg)) {
            Toast.show(res.msg, 1);
        }
    }

    onCallback && onCallback(success, resObj);
}

export const reqSaveProofContactData = async (proofData, onCallback) => {
    //组装参数
    const baseParam = baseParams();
    const params = { ...baseParam, ...proofData };

    //发起请求
    const res = await http.post(UrlSaveProofContactList, params);
    const resCode = parseInt(res.code);
    const resObj = res.obj;
    console.log("reqSaveProofContactData-end: =======");

    //保存
    const success = (resCode === 0);

    //如果有错误，提示
    if (!success) {
        if (!isEmptyString(res.msg)) {
            Toast.show(res.msg, 1);
        }
    }

    onCallback && onCallback(success, resObj);
}

export const reqSaveFace = async (imgUrl, onCallback) => {
    //组装参数
    const params = baseParams();
    params.faceImgUrl = imgUrl;
    params.cardType = "";

    //发起请求
    const res = await http.post(UrlSaveFaceInfo, params);
    const resCode = parseInt(res.code);
    const resObj = res.obj;
    console.log("reqSaveFace-end: =======");

    //保存
    const success = (resCode === 0);

    //如果有错误，提示
    if ((resCode !== 2002) && (resCode !== 2001)) {
        if (!success) {
            if (!isEmptyString(res.msg)) {
                Toast.show(res.msg, 1);
            }
        }
    }
    onCallback && onCallback(success, resObj);
}

export const reqSaveFrequentlyApps = async (appList, onCallback) => {
    //组装参数
    const baseParam = baseParams();
    baseParam.frequentlyUserApp = appList + "";

    //发起请求
    const res = await http.post(UrlSaveFrequentlyApps, baseParam);
    const resCode = parseInt(res.code);
    const resObj = res.obj;
    console.log("reqSaveFrequentlyApps-end: =======");

    //保存
    const success = (resCode === 0);

    //如果有错误，提示
    if (!success) {
        if (!isEmptyString(res.msg)) {
            Toast.show(res.msg, 1);
        }
    }
    onCallback && onCallback(success, resObj);
}

export const reqDataSmsCodeLogin = async (mobile, code, fetchOrderId, onCallback) => {
    //组装参数
    const baseParam = baseParams();
    baseParam.mobile = mobile + "";
    baseParam.code = code + "";
    baseParam.fetchOrderId = fetchOrderId + "";

    //发起请求
    const res = await http.post(UrlDataSmsCodeLogin, baseParam);
    const resCode = parseInt(res.code);
    const resObj = res.obj;
    console.log("reqDataSmsCodeLogin-end: =======");

    //保存
    const success = (resCode === 0);

    //如果有错误，提示
    if (!success) {
        if (!isEmptyString(res.msg)) {
            Toast.show(res.msg, 1)
        }
    }

    onCallback && onCallback(success, resObj);

}

export const reqUploadImage = async (image, onCallback) => {
    //组装参数
    const params = baseParams();

    // const file = {
    //     uri: image,
    //     type: "image/jpeg",
    //     name: "filensddame",
    // }

    //压图片
    const formData = new FormData();
    formData.append('image', image);

    //压参数
    for (const key in params) {
        formData.append(key, params[key]);
    }

    //发起请求
    const res = uploadHttp.post(UrlUploadImage, formData);
    const resCode = parseInt(res.code);
    const resObj = res.obj;
    const url = resObj.url
    console.log("reqUploadImage-end: =======");

    //保存
    const success = (resCode === 0);

    //如果有错误，提示
    if (!success) {
        if (!isEmptyString(res.msg)) {
            Toast.show(res.msg, 1);
        }
    }

    onCallback && onCallback(success, url);
}

export const reqLoanDetailByAmount = async (amount, loanDetailInfo = {}, onCallback) => {
    //贷款等级
    //2000,4000,6000
    let selectRank = "1";
    if (amount === AmountRange.rank2) {
        selectRank = "2";
    } else if (amount === AmountRange.rank3) {
        selectRank = "3";
    }

    //组装参数
    const params = baseParams();
    params.amount = amount;
    params.selectRank = selectRank;

    //发起请求
    const res = await http.post(UrlGetLoanApplyDetailByAmount, params);
    const resCode = parseInt(res.code);
    const resObj = res.obj;
    const success = (resCode === 0);
    console.log("reqLoanDetailByAmount-end:=======");

    //保存
    if (success) {
        //货币符号
        resObj.currency = AppParams.currency;

        if (isEmptyObject(loanDetailInfo)) {
            //测试数据
            resObj.amountList = [AmountRange.rank1, AmountRange.rank2, AmountRange.rank3];
            resObj.daysList = [7, 14, 30];
            resObj.canSelectAmount = true;
            resObj.canSelectDay = false;

            //用户类型 OLD NEW
            const userType = resObj.userType;
            if (userType) {
                resObj.isOldUser = userType === 'OLD';
                resObj.isNewUser = userType === 'NEW';
            } else {
                resObj.isOldUser = false;
                resObj.isNewUser = true;
            }

            //如果是老客，直接显示真实金额
            if (resObj.isOldUser) {
                resObj.amountList = [resObj.amount, resObj.amount, resObj.amount];
            }

            //组装金额
            if (resObj.amountList && resObj.amountList.length > 0) {
                resObj.amountOptions = [];
                let firstCheck = false;
                for (let i = 0; i < resObj.amountList.length; i++) {
                    if (resObj.isOldUser && (i === 0)) {
                        firstCheck = true;
                    } else {
                        firstCheck = false;
                    }
                    resObj.amountOptions[i] = {
                        label: resObj.amountList[i] + "",
                        value: "1",
                        locked: (i !== 0),
                        selected: firstCheck
                    };
                }
            }

            //组装日期
            if (resObj.daysList && resObj.daysList.length > 0) {
                resObj.dayOptions = [];
                for (let i = 0; i < resObj.daysList.length; i++) {
                    resObj.dayOptions[i] = {
                        label: resObj.daysList[i] + "",
                        value: "1",
                        selected: (i === 0)
                    };
                }
            }
        } else {
            resObj.canSelectAmount = loanDetailInfo.canSelectAmount;
            resObj.canSelectDay = loanDetailInfo.canSelectDay;
            resObj.isOldUser = loanDetailInfo.isOldUser;
            resObj.isNewUser = loanDetailInfo.isNewUser;
            resObj.amountOptions = loanDetailInfo.amountOptions;
            resObj.dayOptions = loanDetailInfo.dayOptions;
        }

        // else {
        //     newLoanDetailInfo.amount = resObj.amount
        //     newLoanDetailInfo.days = resObj.days
        //     newLoanDetailInfo.interest = resObj.interest
        //     newLoanDetailInfo.interestAndServiceFee = resObj.interestAndServiceFee
        //     newLoanDetailInfo.interestRate = resObj.interestRate
        //     newLoanDetailInfo.overdueRate = resObj.overdueRate
        //     newLoanDetailInfo.processingFee = resObj.processingFee
        //     newLoanDetailInfo.realAmount = resObj.realAmount
        //     newLoanDetailInfo.repayAmount = resObj.repayAmount
        //     newLoanDetailInfo.repayProFee = resObj.repayProFee
        // }
    }

    //如果有错误，提示
    if (!success) {
        if (!isEmptyString(res.msg)) {
            Toast.show(res.msg, 1)
        }
    }

    onCallback && onCallback(success, resObj);
}

export const reqConfirmLoanApply = async (amount = "", days = "", onCallback) => {
    //贷款等级
    //2000,4000,6000
    let selectRank = "1";
    if (amount === AmountRange.rank2) {
        selectRank = "2";
    } else if (amount === AmountRange.rank3) {
        selectRank = "3";
    }

    //组装参数
    const params = baseParams();
    params.amount = amount;
    params.days = days;
    params.selectRank = selectRank;

    //发起请求
    const res = await http.post(UrlConfirmLoanApply, params);
    const resCode = parseInt(res.code);
    const resObj = res.obj;
    console.log("reqConfirmLoanApply-end: =======");

    //保存
    const success = (resCode === 0);

    //如果有错误，提示
    if (!success) {
        if (!isEmptyString(res.msg)) {
            Toast.show(res.msg, 1);
        }
    }

    onCallback && onCallback(success, resObj);
}

export const reqSendCopyFailSms = async (onCallback) => {
    //组装参数
    const params = baseParams();

    //发起请求
    const res = await http.post(UrlSendContractSms, params);
    const resCode = parseInt(res.code);
    let resObj = {};
    if (res.obj) {
        if (!isString(res.obj)) {
            resObj = res.obj;
        }
    }

    //保存code，登录有用，判断是否为fb
    resObj.resCode = resCode;
    console.log("reqSendCopyFailSms-end: =======");

    //保存
    const success = (resCode === 0);

    //如果有错误，提示
    if ((resCode !== 2002) && (resCode !== 2001)) {
        if (!success) {
            if (!isEmptyString(res.msg)) {
                Toast.show(res.msg, 1);
            }
        }
    }
    onCallback && onCallback(success, resObj);
}
export const reqRepayDetail = async (onCallback) => {
    //组装参数
    const params = baseParams();

    //发起请求
    const res = await http.post(UrlGetReapyDetail, params);
    const resCode = parseInt(res.code);
    const resObj = res.obj;
    resObj.currency = AppParams.currency;

    //增加展期标识
    const deferredFlag = resObj.deferredFlag;
    resObj.canDeferred = (deferredFlag === "YES");

    console.log("reqRepayDetail-end: =======");

    //保存
    const success = (resCode === 0);

    //如果有错误，提示
    if (!success) {
        if (!isEmptyString(res.msg)) {
            Toast.show(res.msg, 1);
        }
    }

    onCallback && onCallback(success, resObj);
}

export const reqRepayUrl = async (onCallback) => {
    //组装参数
    const params = baseParams();

    //发起请求
    const res = await http.post(UrlGetReapyUrl, params);
    const resCode = parseInt(res.code);
    const resObj = res.obj;
    console.log("reqRepayUrl-end: =======");

    //保存
    const success = (resCode === 0);

    //如果有错误，提示
    if (!success) {
        if (!isEmptyString(res.msg)) {
            Toast.show(res.msg, 1);
        }
    }
    onCallback && onCallback(success, resObj);
}

export const reqSendDataSmsCode = async (mobile, onCallback) => {
    //组装参数
    const params = baseParams();
    params.mobile = mobile + "";

    //发起请求
    const res = await http.post(UrlGetDataSmsCode, params);
    const resCode = parseInt(res.code);
    const resObj = res.obj;
    console.log("reqSendDataSmsCode-end: =======");

    //保存
    const success = (resCode === 0);

    //如果有错误，提示
    if (!success) {
        if (!isEmptyString(res.msg)) {
            Toast.show(res.msg, 1);
        }
    }
    onCallback && onCallback(success, resObj);
}